<template>
  <page-card title="业务条线"
             :sub-title="'新增'"
             :need-back="true">
    <slot name="form" />
    <a-row v-if="!$slots.form">
      <a-col :span="24">
        <a-card :bodyStyle="{overflow: 'auto'}">
          <a-form :form="form"
                  :label-col="{ span: 2 }"
                  :wrapper-col="{ span: 22 }">

            <a-form-item label="条线名称">
              <a-input :maxLength="20"
                       placeholder="请输入条线名称"
                       v-decorator="['businessLineName', { rules: [{ required: true, message: '请填写线条名称!' }] }]" />
            </a-form-item>

          </a-form>
        </a-card>
      </a-col>

    </a-row>
    <!--
    <div style="margin-top: 15px;">
      <a-transfer class="tree-transfer"
                  :data-source="dataSource"
                  :target-keys="targetKeys"
                  :selected-keys="checkedKeys"
                  :render="item => item.title"
                  :show-select-all="false"
                  :titles="['组织机构',' 条线范围']"
                  show-search
                  @change="onChange"
                  @search="handleSearch">
        <template slot="children"
                  slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
          <a-tree v-if="direction === 'left'"
                  blockNode
                  checkable
                  checkStrictly
                  :checkedKeys="[...selectedKeys, ...targetKeys]"
                  :load-data="getUnitTreeData"
                  :tree-data="treeData"
                  @check="
                    (_, props) => {
                      onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                  "
                  @select="
                    (_, props) => {
                      onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                  " />
          <template v-else>
            <a-table :data-source="tableSource"
                     :columns="tableColumns"
                     :rowKey="(record,index)=> record.key"
                     :pagination="false"
                     :row-selection="
                       getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                     "></a-table>
          </template>
        </template>
      </a-transfer>
    </div>
    -->
    <CustomTransfer @change="onChangeTransfer" />
    <div style="text-align:center; padding:30px">
      <a-space size="small">
        <slot name="buttons" />
        <template v-if="!$slots.buttons">
          <a-button v-if="$route.query.id && hasPermission('delete')"
                    action
                    @click="handleDelete"
                    style="width:80px;">删除</a-button>
          <a-button type="primary"
                    action
                    @click="handleSave"
                    style="width:80px;">保存</a-button>
        </template>
      </a-space>
    </div>
  </page-card>
</template>

<script>
import Vue from 'vue'
import { Card, message } from 'ant-design-vue'
import ArrayUtil from '@zh/common-utils/utils/array'
import clone from 'clone'
import { del, unituser, save } from '../../api/businessline/index'
import CustomTransfer from './CustomTransfer.vue'

Vue.use(Card)

/* const treeData = [
  { key: '0-0', title: '0-0',isLeaf:false },
  {
    key: '0-1',
    title: '0-1',
    children: [
      { key: '0-1-0', title: '0-1-0' },
      { key: '0-1-1', title: '0-1-1' }
    ]
  },
  { key: '0-2', title: '0-3' }
] */

export default {
  props: {
    onSave: {
      type: Function,
      default: null
    },
    onDelete: {
      type: Function,
      default: null
    }
  },
  components: {
    CustomTransfer
  },
  data () {
    return {
      targetKeys: [],
      checkedKeys: [],
      dataSource: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
      data: [],
      unituserlist: [],
      tableSource: [],
      tableColumns: [
        { title: '', dataIndex: 'name' },
        { title: '', dataIndex: 'type' }
      ],
      zcyblist: [], // 暂存右边list的数据
      xztablist: [],
      listDisabled: false,
      itemSelectAll: [],
      treeData: [],
      businessLineRange: '',
      businessLineRanges: []
    }
  },

  // computed: {
  // 	treeData() {
  // 		return this.handleTreeData(this.data, this.targetKeys)
  // 	}
  // },
  created () {
    /* this.data = [
      { key: '33', title: '33', pid: '0' },
      { key: '44', title: '44', pid: '0' },
      { key: '55', title: '55', pid: '0' }
    ]

    this.flatten(JSON.parse(JSON.stringify(this.data))) */
    // this.unituserpage('')
    // this.targetKeys = ['1666379693101678593']
  },
  methods: {
    // unituserpage (obj) {
    //   const param = { nameall: obj }
    //   unituser(param).then((rep) => {
    //     this.data = rep.unitusertree
    //     if (obj == '') {
    //       this.unituserlist = rep.unituserlist
    //     }
    //     this.flatten(JSON.parse(JSON.stringify(this.data)))
    //     this.treeData = this.handleTreeData(this.data, this.targetKeys)
    //   })
    // },
    // flatten (list = []) {
    //   list.forEach((item) => {
    //     this.dataSource.push(item)
    //     this.flatten(item.children)
    //   })
    // },
    // handleTreeData (data, targetKeys = [], value = true) {
    //   data.forEach((item) => {
    //     item.disabled = targetKeys.includes(item.key)
    //     if (item.children) {
    //       this.handleTreeData(item.children, targetKeys, value)
    //     }
    //   })
    //   return data
    // },
    // 根据勾选的节点将节点中下的所有子节点设置为禁用并清空勾选的子节点值
    // setChildNodeDisabled (data, keys = [], isCheckAction = false) {
    //   data.forEach((item) => {
    //     if (item.children) {
    //       const isDisabled = keys.includes(item.key) || item.disabled
    //       item.children = item.children.map((node) => {
    //         /**
    //          * 1. 判断父节点item是否包含在选的keys中，如果存在，则需要将所有的子节点设置为禁用状态
    //          * 2. 如果是节点移动操作时，需要判断node子节点是否包含在勾选的keys数组，如果存在，则需要将该子节点设置成禁用状态
    //          */
    //         node.disabled = isDisabled || (!isCheckAction && keys.includes(node.key))
    //         return node
    //       })
    //       // 是否需要删除子节点操作
    //       if (isCheckAction && isDisabled) {
    //         for (const node of item.children) {
    //           const index = keys.findIndex(key => {
    //             return key === node.key
    //           })
    //           if (index > -1) {
    //             keys.splice(index, 1)
    //           }
    //         }
    //       }
    //       this.setChildNodeDisabled(item.children, keys, isCheckAction)
    //     }
    //   })
    //   return data
    // },
    handleSave () {
      this.form.validateFields((err, values) => {
        console.log('err', err)
        let name = values.businessLineName
        if (name == null || name.trim() == '') {
          return
        }
        if (this.businessLineRanges.length == 0) {
          message.info('请添加线条范围！')
          return
        }
        const params = {
          businessLineName: name,
          businessLineRange: this.businessLineRange,
          businessLineRanges: this.businessLineRanges
        }
        save(params).then((response) => {
          this.$router.push({
            path: '/businessline'
          })
        })
      })
    },
    onChangeTransfer (data = []) {
      this.businessLineRange = data.reduce((res, item) => {
        res += `${item.title}、`
        return res
      }, '')
      this.businessLineRange = this.businessLineRange.substring(0, this.businessLineRange.length - 1)
      this.businessLineRanges = []
      for (const item of data) {
        this.businessLineRanges.push({
          businessLineRangeId: item.key,
          businessLineRange: item.title,
          businessLineRangeType: item.type
        })
      }
    }
    // handleDelete () {
    //   const me = this
    //   me.confirm({
    //     content: '确定删除？',
    //     okText: '是',
    //     cancelText: '否',
    //     onOk () {
    //       if (me.onDelete != null) {
    //         me.onDelete(me.form.getFieldValue('id'), me.form).then((res) => {
    //           me.$router.go(-1)
    //         })
    //       } else {
    //         del(me.form.getFieldValue('id')).then((res) => {
    //           me.$router.go(-1)
    //         })
    //       }
    //     }
    //   })
    // },

    // onChange (targetKeys, direction, moveKeys) {
    //   const _this = this
    //   const tabs = _this.xztablist
    //   this.checkedKeys = []
    //   if (tabs.length > 0 && direction == 'left') {
    //     const keys = _this.targetKeys
    //     let datas = []
    //     for (var i = 0; i < keys.length; i++) {
    //       var flg = true
    //       for (var j = 0; j < tabs.length; j++) {
    //         if (keys[i] == tabs[j].key) {
    //           flg = false
    //         }
    //       }
    //       if (flg) {
    //         datas.push(keys[i])
    //       }
    //     }
    //     targetKeys = datas
    //   }
    //   _this.targetKeys = targetKeys
    //   _this.zcyblist = targetKeys
    //   const uulist = _this.unituserlist
    //   let tablist = []
    //   for (var i = 0; i < uulist.length; i++) {
    //     var flg = false
    //     for (var j = 0; j < targetKeys.length; j++) {
    //       if (uulist[i].key == targetKeys[j]) {
    //         flg = true
    //       }
    //     }
    //     if (flg) {
    //       let types = ''
    //       if (uulist[i].type == '2') {
    //         types = '单位'
    //       } else if (uulist[i].type == '3') {
    //         types = '部门'
    //       } else if (uulist[i].type == '10') {
    //         types = '人员'
    //       }
    //       let aa = { name: uulist[i].title, type: types, key: uulist[i].key }
    //       tablist.push(aa)
    //     }
    //   }
    //   _this.tableSource = tablist
    //   _this.xztablist = []
    //   this.handleTreeData(this.data, targetKeys)
    //   this.setChildNodeDisabled(this.data, targetKeys)
    // },
    // onChecked (_, e, checkedKeys, itemSelect) {
    //   const { eventKey } = e.node
    //   const index = this.checkedKeys.indexOf(eventKey)
    //   if (index > -1) {
    //     this.checkedKeys.splice(index, 1)
    //   } else {
    //     this.checkedKeys.push(eventKey)
    //   }
    //   this.setChildNodeDisabled(this.data, this.checkedKeys, true)
    // },
    // handleSearch (dir, value) {
    //   if (dir == 'left') {
    //     this.dataSource = []
    //     this.unituserpage(value, '')
    //   }
    //   if (dir == 'right') {
    //     const xzlist = this.zcyblist
    //     let zslist = []
    //     const unituserlists = this.unituserlist
    //     if (value != null && value.trim() != '') {
    //       for (var i = 0; i < unituserlists.length; i++) {
    //         var flg = false
    //         for (var j = 0; j < xzlist.length; j++) {
    //           if (unituserlists[i].key == xzlist[j]) {
    //             flg = true
    //           }
    //         }
    //         if (flg) {
    //           zslist.push(unituserlists[i])
    //         }
    //       }
    //       let showdata = []
    //       for (var i = 0; i < zslist.length; i++) {
    //         if (zslist[i].title.indexOf(value) != -1) {
    //           showdata.push(zslist[i].key)
    //         }
    //       }

    //       this.targetKeys = showdata
    //       const uulist = this.unituserlist
    //       var tablist = []
    //       for (var i = 0; i < uulist.length; i++) {
    //         var flg = false
    //         for (var j = 0; j < showdata.length; j++) {
    //           if (uulist[i].key == showdata[j]) {
    //             flg = true
    //           }
    //         }
    //         if (flg) {
    //           var types = ''
    //           if (uulist[i].type == '2') {
    //             types = '单位'
    //           } else if (uulist[i].type == '3') {
    //             types = '部门'
    //           } else if (uulist[i].type == '10') {
    //             types = '人员'
    //           }
    //           var aa = { name: uulist[i].title, type: types }
    //           tablist.push(aa)
    //         }
    //       }
    //       this.tableSource = tablist
    //     } else {
    //       const showdata = this.zcyblist
    //       this.targetKeys = showdata
    //       const uulist = this.unituserlist
    //       var tablist = []
    //       for (var i = 0; i < uulist.length; i++) {
    //         var flg = false
    //         for (var j = 0; j < showdata.length; j++) {
    //           if (uulist[i].key == showdata[j]) {
    //             flg = true
    //           }
    //         }
    //         if (flg) {
    //           var types = ''
    //           if (uulist[i].type == '2') {
    //             types = '单位'
    //           } else if (uulist[i].type == '3') {
    //             types = '部门'
    //           } else if (uulist[i].type == '10') {
    //             types = '人员'
    //           }
    //           var aa = { name: uulist[i].title, type: types }
    //           tablist.push(aa)
    //         }
    //       }
    //       this.tableSource = tablist
    //     }
    //   }
    // },
    // onSelectChange (selectedRowKeys) {

    //   this.selectedRowKeys = selectedRowKeys
    // },

    // getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
    //   const _this = this
    //   return {
    //     selectedRowKeys: this.checkedKeys,
    //     getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
    //     onSelectAll (selected, selectedRows) {
    //       const treeSelectedKeys = selectedRows
    //         .filter(item => !item.disabled)
    //         .map(({ key }) => key)
    //       const diffKeys = selected
    //         ? difference(treeSelectedKeys, selectedKeys)
    //         : difference(selectedKeys, treeSelectedKeys)

    //       itemSelectAll(diffKeys, selected)
    //     },
    //     onSelect (row, selected) {
    //       if (selected) {
    //         // var tabs = []
    //         // tabs.push(aa)
    //         _this.xztablist.push(row)
    //         _this.checkedKeys.push(row.key)
    //       } else {
    //         const dels = _this.xztablist
    //         let tabs = []
    //         for (let i = 0; i < dels.length; i++) {
    //           let flg = true
    //           if (dels[i].key == row.key) {
    //             flg = false
    //           }
    //           if (flg) {
    //             tabs.push(dels[i])
    //           }
    //         }
    //         _this.xztablist = tabs
    //         const index = _this.checkedKeys.indexOf(row.key)
    //         if (index > -1) {
    //           _this.checkedKeys.splice(index, 1)
    //         }
    //       }
    //       itemSelect(row.key, selected)
    //     }
    //   }
    // },

    // getUnitTreeData (treeNode) {
    //   const _this = this
    //   const param = { parentId: treeNode.dataRef.key }
    //   return new Promise((resolve) => {
    //     unituser(param).then((rep) => {
    //       if (rep.unitusertree.length > 0) {
    //         treeNode.dataRef.children = rep.unitusertree
    //         // _this.treeData = [..._this.treeData]
    //         _this.data = _this.treeData
    //         const list = rep.unituserlist
    //         for (let i = 0; i < list.length; i++) {
    //           _this.unituserlist.push(list[i])
    //         }
    //         _this.flatten(JSON.parse(JSON.stringify(_this.data)))
    //         this.setChildNodeDisabled(this.data, this.checkedKeys, true)
    //         resolve()
    //       } else {
    //         resolve()
    //       }
    //     })
    //   })
    // }
  }
}
</script>

<style  lang="less" scoped>
::v-deep .ant-checkbox-group-item {
  width: 100%;
  padding: 5px 0;
}
.tree-transfer .ant-transfer-list:first-child {
  width: 50%;
  flex: none;
}
/deep/.ant-table-thead {
  display: none;
}
/deep/.ant-transfer-customize-list {
  .ant-transfer-list {
    .ant-transfer-list-header {
      padding: 15px 12px;
      .ant-checkbox-wrapper {
        .ant-checkbox {
          display: none;
        }
      }
    }
    .ant-transfer-list-body-search-wrapper {
      position: absolute;
      top: -42px;
      left: 6px;
      width: 280px;
    }
    .ant-transfer-list-header-title {
      position: relative;
    }
    .ant-transfer-list-header-selected {
      display: flex;
      justify-content: flex-end;
      & > span:first-child {
        display: none;
      }
    }
  }
}
</style>
